<!DOCTYPE html><html lang="zh-CN" data-theme="dark"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>Gin框架 | J.のblog</title><meta name="keywords" content="云原生,golang"><meta name="author" content="J."><meta name="copyright" content="J."><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#0d0d0d"><meta name="description" content="Gin框架一、Gin框架使用1、Gin框架简介Gin是一个用Go语言编写的Web框架。Gin框架拥有很好的性能，借助高性能的HttpRouter包，运行速度得到了极大的提升。 2、Gin框架安装与示例（1）、安装 go get -u github.com&#x2F;gin-gonic&#x2F;gin  （2）、示例 func Get(c *gin.Context) &amp;#123;     name :&#x3D; c.Quer">
<meta property="og:type" content="article">
<meta property="og:title" content="Gin框架">
<meta property="og:url" content="http://dycloudnavite.love/2023/06/23/Gin%E6%A1%86%E6%9E%B6/index.html">
<meta property="og:site_name" content="J.のblog">
<meta property="og:description" content="Gin框架一、Gin框架使用1、Gin框架简介Gin是一个用Go语言编写的Web框架。Gin框架拥有很好的性能，借助高性能的HttpRouter包，运行速度得到了极大的提升。 2、Gin框架安装与示例（1）、安装 go get -u github.com&#x2F;gin-gonic&#x2F;gin  （2）、示例 func Get(c *gin.Context) &amp;#123;     name :&#x3D; c.Quer">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://dycloudnavite.love/img/golang.png">
<meta property="article:published_time" content="2023-06-23T06:32:00.000Z">
<meta property="article:modified_time" content="2023-08-30T03:23:03.958Z">
<meta property="article:author" content="J.">
<meta property="article:tag" content="云原生">
<meta property="article:tag" content="golang">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://dycloudnavite.love/img/golang.png"><link rel="shortcut icon" href="/dujie5416/img/touxiang.png"><link rel="canonical" href="http://dycloudnavite.love/2023/06/23/Gin%E6%A1%86%E6%9E%B6/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/dujie5416/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/dujie5416/',
  algolia: {"appId":"9GWB2VV7GN","apiKey":"dac56ec5b0b1f45281251ee59db4d637","indexName":"blog","hits":{"per_page":6},"languages":{"input_placeholder":"搜索文章","hits_empty":"找不到您查询的内容：${query}","hits_stats":"找到 ${hits} 条结果，用时 ${time} 毫秒"}},
  localSearch: undefined,
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Gin框架',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-08-30 11:23:03'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/xxx.css"><link rel="stylesheet" href="/css/universe.css"><link rel="stylesheet" href="/css/custom.css"><style type="text/css">#toggle-sidebar {bottom: 80px}</style><link rel="stylesheet" href="https://fastly.jsdelivr.net/gh/tzy13755126023/BLOG_SOURCE/css/function.min.css"><link rel="stylesheet" href="/css/rightMenu.css"><style type="text/css">#toggle-sidebar {left:100px}</style><!-- hexo injector head_end start --><link rel="stylesheet" href="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/clock.min.css" /><!-- hexo injector head_end end --><meta name="generator" content="Hexo 6.2.0"><link rel="alternate" href="/dujie5416/atom.xml" title="J.のblog" type="application/atom+xml">
</head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/dujie5416/img/touxiang.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/dujie5416/archives/"><div class="headline">文章</div><div class="length-num">73</div></a><a href="/dujie5416/tags/"><div class="headline">标签</div><div class="length-num">17</div></a><a href="/dujie5416/categories/"><div class="headline">分类</div><div class="length-num">11</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/dujie5416/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/dujie5416/img/longzhu.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/dujie5416/">J.のblog</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/dujie5416/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Gin框架</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-06-23T06:32:00.000Z" title="发表于 2023-06-23 14:32:00">2023-06-23</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-08-30T03:23:03.958Z" title="更新于 2023-08-30 11:23:03">2023-08-30</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/dujie5416/categories/golang/">golang</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Gin框架"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="Gin框架"><a href="#Gin框架" class="headerlink" title="Gin框架"></a>Gin框架</h1><h3 id="一、Gin框架使用"><a href="#一、Gin框架使用" class="headerlink" title="一、Gin框架使用"></a>一、Gin框架使用</h3><h5 id="1、Gin框架简介"><a href="#1、Gin框架简介" class="headerlink" title="1、Gin框架简介"></a>1、Gin框架简介</h5><p>Gin是一个用Go语言编写的Web框架。Gin框架拥有很好的性能，借助高性能的<strong>HttpRouter</strong>包，运行速度得到了极大的提升。</p>
<h5 id="2、Gin框架安装与示例"><a href="#2、Gin框架安装与示例" class="headerlink" title="2、Gin框架安装与示例"></a>2、Gin框架安装与示例</h5><p>（1）、安装</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">go</span> get <span class="token operator">-</span>u github<span class="token punctuation">.</span>com<span class="token operator">/</span>gin<span class="token operator">-</span>gonic<span class="token operator">/</span>gin
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>（2）、示例</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">Get</span><span class="token punctuation">(</span>c <span class="token operator">*</span>gin<span class="token punctuation">.</span>Context<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    name <span class="token operator">:=</span> c<span class="token punctuation">.</span><span class="token function">Query</span><span class="token punctuation">(</span><span class="token string">"name"</span><span class="token punctuation">)</span> <span class="token comment">// 从url中获取name字段</span>
    <span class="token comment">// 返回字符串格式的数据</span>
    <span class="token comment">//c.String(200, "欢迎您：%s", name)</span>
    <span class="token comment">// c.JSON ：返回JSON格式的数据</span>
    c<span class="token punctuation">.</span><span class="token function">JSON</span><span class="token punctuation">(</span><span class="token number">200</span><span class="token punctuation">,</span> gin<span class="token punctuation">.</span>H<span class="token punctuation">&#123;</span>
        <span class="token string">"code"</span><span class="token punctuation">:</span> http<span class="token punctuation">.</span>StatusOK<span class="token punctuation">,</span>
        <span class="token string">"msg"</span><span class="token punctuation">:</span>  <span class="token string">"返回信息"</span><span class="token punctuation">,</span>
        <span class="token string">"data"</span><span class="token punctuation">:</span> <span class="token string">"欢迎您"</span> <span class="token operator">+</span> name<span class="token punctuation">,</span>
    <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token comment">// 创建一个默认的路由引擎</span>
    r <span class="token operator">:=</span> gin<span class="token punctuation">.</span><span class="token function">Default</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token comment">// GET：请求方式：/hello：请求的路径，当客户端以Get方法请求/hello路径时，会执行后面的函数</span>
    r<span class="token punctuation">.</span><span class="token function">GET</span><span class="token punctuation">(</span><span class="token string">"/hello"</span><span class="token punctuation">,</span> Get<span class="token punctuation">)</span>
    <span class="token comment">//r.POST("/user/login", Post)</span>
    <span class="token comment">// 启动HTTP服务，默认在0.0.0.0:8080启动服务</span>
    r<span class="token punctuation">.</span><span class="token function">Run</span><span class="token punctuation">(</span><span class="token string">"127.0.0.1:8090"</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><img src="/images/jrXRa7egP8ZJprErQGCJzH2QvcwBf7f_gjPuRZLOiGA.png" alt="image"></p>
<h5 id="3、Gin路由和控制器"><a href="#3、Gin路由和控制器" class="headerlink" title="3、Gin路由和控制器"></a>3、Gin路由和控制器</h5><p>路由：一个HTTP请求找到对应 的处理器函数的过程。处理器函数主要负责执行HTTP请求和响应任务。如下代码中的goLogin() 函数就是Gin的处理器函数。</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">goLogin</span><span class="token punctuation">(</span>context <span class="token operator">*</span>gin<span class="token punctuation">.</span>Context<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    name <span class="token operator">:=</span> context<span class="token punctuation">.</span><span class="token function">PostForm</span><span class="token punctuation">(</span><span class="token string">"username"</span><span class="token punctuation">)</span>
    password <span class="token operator">:=</span> context<span class="token punctuation">.</span><span class="token function">PostForm</span><span class="token punctuation">(</span><span class="token string">"password"</span><span class="token punctuation">)</span>
    <span class="token keyword">if</span> name <span class="token operator">==</span> <span class="token string">"dujie"</span> <span class="token operator">&amp;&amp;</span> password <span class="token operator">==</span> <span class="token string">"123456"</span> <span class="token punctuation">&#123;</span>
        context<span class="token punctuation">.</span><span class="token function">JSON</span><span class="token punctuation">(</span><span class="token number">200</span><span class="token punctuation">,</span> gin<span class="token punctuation">.</span>H<span class="token punctuation">&#123;</span>
            <span class="token string">"code"</span><span class="token punctuation">:</span>     http<span class="token punctuation">.</span>StatusOK<span class="token punctuation">,</span>
            <span class="token string">"msg"</span><span class="token punctuation">:</span>      <span class="token string">"登录成功"</span><span class="token punctuation">,</span>
            <span class="token string">"username"</span><span class="token punctuation">:</span> name<span class="token punctuation">,</span>
        <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
        context<span class="token punctuation">.</span><span class="token function">JSON</span><span class="token punctuation">(</span>http<span class="token punctuation">.</span>StatusOK<span class="token punctuation">,</span> gin<span class="token punctuation">.</span>H<span class="token punctuation">&#123;</span>
            <span class="token string">"code"</span><span class="token punctuation">:</span> <span class="token number">403</span><span class="token punctuation">,</span>
            <span class="token string">"msg"</span><span class="token punctuation">:</span>  <span class="token string">"用户或密码错误"</span><span class="token punctuation">,</span>
        <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span>
    <span class="token comment">//context.String(200, "username=%s password=%s", name, password)</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>####### <strong>（1）、路由规则</strong><br>一条路由规则由HTTP请求方法、URL路径、处理器函数这3个部分组成</p>
<ol>
<li><strong>HTTP请求方法</strong></li>
</ol>
<p>常用的HTTP请求方法有GET、POST、PUT、DELETE等</p>
<ol start="2">
<li><strong>URL路径</strong></li>
</ol>
<p>Gin框架的URL路径有3种写法</p>
<p>1）静态URL路径，即不带任何参数的URL路径，例如：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token operator">/</span>users<span class="token operator">/</span>dujie
<span class="token operator">/</span>user<span class="token operator">/</span><span class="token number">1</span>
<span class="token operator">/</span>article<span class="token operator">/</span><span class="token number">6</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>2）带路径参数的URL路径，URL路径中带有参数，参数由英文冒号”:” 跟着一个字符串定义。例如：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">定义参数<span class="token punctuation">:</span>id<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>3）带星号(*)模糊匹配参数的URL路径</p>
<p>星号（*）代表匹配任意路径的意思。必须在 * 后面指定一个参数名，之后可以通过这个参数获取 * 号匹配的内容。例如：”&#x2F;user&#x2F;*path” 可以通过path参数获取 * 号匹配的内容，如&#x2F;user&#x2F;1 、&#x2F;user&#x2F;dujie&#x2F;comment&#x2F;1等。</p>
<p> </p>
<ol start="3">
<li><strong>处理器函数</strong></li>
</ol>
<p>Gin框架的处理器函数定义如下：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">type</span> HandlerFunc <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token operator">*</span>Context<span class="token punctuation">)</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>处理器函数接受一个上下文参数。可以通过上下文参数获取HTTP的请求参数，返回HTTP请求的响应。</p>
<p>####### <strong>（1）、分组路由</strong><br>在做API开发时，如果要支持多个API版本，则可以通过分组路由来处理API版本。</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token comment">// 创建一个默认的路由引擎</span>
    r <span class="token operator">:=</span> gin<span class="token punctuation">.</span><span class="token function">Default</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token comment">// GET：请求方式：/hello：请求的路径，当客户端以Get方法请求/hello路径时，会执行后面的函数</span>
    v1 <span class="token operator">:=</span> r<span class="token punctuation">.</span><span class="token function">Group</span><span class="token punctuation">(</span><span class="token string">"/v1"</span><span class="token punctuation">)</span>
    <span class="token punctuation">&#123;</span>
        v1<span class="token punctuation">.</span><span class="token function">POST</span><span class="token punctuation">(</span><span class="token string">"/login"</span><span class="token punctuation">,</span> goLogin<span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span>
    v2 <span class="token operator">:=</span> r<span class="token punctuation">.</span><span class="token function">Group</span><span class="token punctuation">(</span><span class="token string">"/v2"</span><span class="token punctuation">)</span>
    <span class="token punctuation">&#123;</span>
        v2<span class="token punctuation">.</span><span class="token function">POST</span><span class="token punctuation">(</span><span class="token string">"/login"</span><span class="token punctuation">,</span> goLogin<span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span>
    r<span class="token punctuation">.</span><span class="token function">Run</span><span class="token punctuation">(</span><span class="token string">":8090"</span><span class="token punctuation">)</span>

<span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token function">goLogin</span><span class="token punctuation">(</span>context <span class="token operator">*</span>gin<span class="token punctuation">.</span>Context<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"1："</span><span class="token punctuation">,</span> context<span class="token punctuation">.</span>Params<span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"2："</span><span class="token punctuation">,</span> context<span class="token punctuation">.</span>Request<span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"3："</span><span class="token punctuation">,</span> context<span class="token punctuation">.</span>Keys<span class="token punctuation">)</span>

    name <span class="token operator">:=</span> context<span class="token punctuation">.</span><span class="token function">PostForm</span><span class="token punctuation">(</span><span class="token string">"username"</span><span class="token punctuation">)</span>
    password <span class="token operator">:=</span> context<span class="token punctuation">.</span><span class="token function">PostForm</span><span class="token punctuation">(</span><span class="token string">"password"</span><span class="token punctuation">)</span>
    <span class="token keyword">if</span> name <span class="token operator">==</span> <span class="token string">"dujie"</span> <span class="token operator">&amp;&amp;</span> password <span class="token operator">==</span> <span class="token string">"123456"</span> <span class="token punctuation">&#123;</span>
        context<span class="token punctuation">.</span><span class="token function">JSON</span><span class="token punctuation">(</span><span class="token number">200</span><span class="token punctuation">,</span> gin<span class="token punctuation">.</span>H<span class="token punctuation">&#123;</span>
            <span class="token string">"code"</span><span class="token punctuation">:</span>     http<span class="token punctuation">.</span>StatusOK<span class="token punctuation">,</span>
            <span class="token string">"msg"</span><span class="token punctuation">:</span>      <span class="token string">"登录成功"</span><span class="token punctuation">,</span>
            <span class="token string">"username"</span><span class="token punctuation">:</span> name<span class="token punctuation">,</span>
        <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
        context<span class="token punctuation">.</span><span class="token function">JSON</span><span class="token punctuation">(</span>http<span class="token punctuation">.</span>StatusOK<span class="token punctuation">,</span> gin<span class="token punctuation">.</span>H<span class="token punctuation">&#123;</span>
            <span class="token string">"code"</span><span class="token punctuation">:</span> <span class="token number">403</span><span class="token punctuation">,</span>
            <span class="token string">"msg"</span><span class="token punctuation">:</span>  <span class="token string">"用户或密码错误"</span><span class="token punctuation">,</span>
        <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span>
    <span class="token comment">//context.String(200, "username=%s password=%s", name, password)</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>上面的例子会将注册下面的路由信息：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token operator">/</span>v1<span class="token operator">/</span>login
<span class="token operator">/</span>v2<span class="token operator">/</span>login<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<h5 id="4、Gin处理请求参数"><a href="#4、Gin处理请求参数" class="headerlink" title="4、Gin处理请求参数"></a>4、Gin处理请求参数</h5><p>（1）、获取GET请求参数</p>
<p>Gin获取GET请求参数常用方法如下：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// Query returns the keyed url query value if it exists,</span>
<span class="token comment">// otherwise it returns an empty string `("")`.</span>
<span class="token comment">// It is shortcut for `c.Request.URL.Query().Get(key)`</span>
<span class="token comment">//</span>
<span class="token comment">//	    GET /path?id=1234&amp;name=Manu&amp;value=</span>
<span class="token comment">//		   c.Query("id") == "1234"</span>
<span class="token comment">//		   c.Query("name") == "Manu"</span>
<span class="token comment">//		   c.Query("value") == ""</span>
<span class="token comment">//		   c.Query("wtf") == ""</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>Context<span class="token punctuation">)</span> <span class="token function">Query</span><span class="token punctuation">(</span>key <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token punctuation">(</span>value <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	value<span class="token punctuation">,</span> <span class="token boolean">_</span> <span class="token operator">=</span> c<span class="token punctuation">.</span><span class="token function">GetQuery</span><span class="token punctuation">(</span>key<span class="token punctuation">)</span>
	<span class="token keyword">return</span>
<span class="token punctuation">&#125;</span>
<span class="token comment">// DefaultQuery returns the keyed url query value if it exists,</span>
<span class="token comment">// otherwise it returns the specified defaultValue string.</span>
<span class="token comment">// See: Query() and GetQuery() for further information.</span>
<span class="token comment">//</span>
<span class="token comment">//	GET /?name=Manu&amp;lastname=</span>
<span class="token comment">//	c.DefaultQuery("name", "unknown") == "Manu"</span>
<span class="token comment">//	c.DefaultQuery("id", "none") == "none"</span>
<span class="token comment">//	c.DefaultQuery("lastname", "none") == ""</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>Context<span class="token punctuation">)</span> <span class="token function">DefaultQuery</span><span class="token punctuation">(</span>key<span class="token punctuation">,</span> defaultValue <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token builtin">string</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">if</span> value<span class="token punctuation">,</span> ok <span class="token operator">:=</span> c<span class="token punctuation">.</span><span class="token function">GetQuery</span><span class="token punctuation">(</span>key<span class="token punctuation">)</span><span class="token punctuation">;</span> ok <span class="token punctuation">&#123;</span>
		<span class="token keyword">return</span> value
	<span class="token punctuation">&#125;</span>
	<span class="token keyword">return</span> defaultValue
<span class="token punctuation">&#125;</span>
<span class="token comment">// DefaultQuery returns the keyed url query value if it exists,</span>
<span class="token comment">// otherwise it returns the specified defaultValue string.</span>
<span class="token comment">// See: Query() and GetQuery() for further information.</span>
<span class="token comment">//</span>
<span class="token comment">//	GET /?name=Manu&amp;lastname=</span>
<span class="token comment">//	c.DefaultQuery("name", "unknown") == "Manu"</span>
<span class="token comment">//	c.DefaultQuery("id", "none") == "none"</span>
<span class="token comment">//	c.DefaultQuery("lastname", "none") == ""</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>Context<span class="token punctuation">)</span> <span class="token function">DefaultQuery</span><span class="token punctuation">(</span>key<span class="token punctuation">,</span> defaultValue <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token builtin">string</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">if</span> value<span class="token punctuation">,</span> ok <span class="token operator">:=</span> c<span class="token punctuation">.</span><span class="token function">GetQuery</span><span class="token punctuation">(</span>key<span class="token punctuation">)</span><span class="token punctuation">;</span> ok <span class="token punctuation">&#123;</span>
		<span class="token keyword">return</span> value
	<span class="token punctuation">&#125;</span>
	<span class="token keyword">return</span> defaultValue
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>（2）、获取POST请求参数</strong></p>
<p>Gin获取POST请求参数的常用方法如下：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// PostForm returns the specified key from a POST urlencoded form or multipart form</span>
<span class="token comment">// when it exists, otherwise it returns an empty string `("")`.</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>Context<span class="token punctuation">)</span> <span class="token function">PostForm</span><span class="token punctuation">(</span>key <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token punctuation">(</span>value <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	value<span class="token punctuation">,</span> <span class="token boolean">_</span> <span class="token operator">=</span> c<span class="token punctuation">.</span><span class="token function">GetPostForm</span><span class="token punctuation">(</span>key<span class="token punctuation">)</span>
	<span class="token keyword">return</span>
<span class="token punctuation">&#125;</span>
<span class="token comment">// DefaultPostForm returns the specified key from a POST urlencoded form or multipart form</span>
<span class="token comment">// when it exists, otherwise it returns the specified defaultValue string.</span>
<span class="token comment">// See: PostForm() and GetPostForm() for further information.</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>Context<span class="token punctuation">)</span> <span class="token function">DefaultPostForm</span><span class="token punctuation">(</span>key<span class="token punctuation">,</span> defaultValue <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token builtin">string</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">if</span> value<span class="token punctuation">,</span> ok <span class="token operator">:=</span> c<span class="token punctuation">.</span><span class="token function">GetPostForm</span><span class="token punctuation">(</span>key<span class="token punctuation">)</span><span class="token punctuation">;</span> ok <span class="token punctuation">&#123;</span>
		<span class="token keyword">return</span> value
	<span class="token punctuation">&#125;</span>
	<span class="token keyword">return</span> defaultValue
<span class="token punctuation">&#125;</span>
<span class="token comment">// GetPostForm is like PostForm(key). It returns the specified key from a POST urlencoded</span>
<span class="token comment">// form or multipart form when it exists `(value, true)` (even when the value is an empty string),</span>
<span class="token comment">// otherwise it returns ("", false).</span>
<span class="token comment">// For example, during a PATCH request to update the user's email:</span>
<span class="token comment">//</span>
<span class="token comment">//	    email=mail@example.com  -->  ("mail@example.com", true) := GetPostForm("email") // set email to "mail@example.com"</span>
<span class="token comment">//		   email=                  -->  ("", true) := GetPostForm("email") // set email to ""</span>
<span class="token comment">//	                            -->  ("", false) := GetPostForm("email") // do nothing with email</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>Context<span class="token punctuation">)</span> <span class="token function">GetPostForm</span><span class="token punctuation">(</span>key <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token punctuation">(</span><span class="token builtin">string</span><span class="token punctuation">,</span> <span class="token builtin">bool</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">if</span> values<span class="token punctuation">,</span> ok <span class="token operator">:=</span> c<span class="token punctuation">.</span><span class="token function">GetPostFormArray</span><span class="token punctuation">(</span>key<span class="token punctuation">)</span><span class="token punctuation">;</span> ok <span class="token punctuation">&#123;</span>
		<span class="token keyword">return</span> values<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">,</span> ok
	<span class="token punctuation">&#125;</span>
	<span class="token keyword">return</span> <span class="token string">""</span><span class="token punctuation">,</span> <span class="token boolean">false</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>使用方法示例：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// 跟PostForm的区别是：可以通过第2个参数设置参数默认值</span>
name <span class="token operator">:=</span> context<span class="token punctuation">.</span><span class="token function">DefaultPostForm</span><span class="token punctuation">(</span><span class="token string">"username"</span><span class="token punctuation">,</span> <span class="token string">"name"</span><span class="token punctuation">)</span>
<span class="token comment">//name := context.PostForm("username")</span>
password<span class="token punctuation">,</span> ok <span class="token operator">:=</span> context<span class="token punctuation">.</span><span class="token function">GetPostForm</span><span class="token punctuation">(</span><span class="token string">"password"</span><span class="token punctuation">)</span>
<span class="token keyword">if</span> <span class="token operator">!</span>ok <span class="token punctuation">&#123;</span>
    log<span class="token punctuation">.</span><span class="token function">Panicln</span><span class="token punctuation">(</span><span class="token string">"参数不存在"</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>（3）、获取URL路径参数</strong></p>
<p>Gin获取URL路径参数是指，获取&#x2F;user&#x2F;:id 这类路由绑定的参数。&#x2F;user&#x2F;:id 绑定了一个参数id。获取URL路径参数的函数如下：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>Context<span class="token punctuation">)</span> <span class="token function">Param</span><span class="token punctuation">(</span>key <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token builtin">string</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">return</span> c<span class="token punctuation">.</span>Params<span class="token punctuation">.</span><span class="token function">ByName</span><span class="token punctuation">(</span>key<span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">r<span class="token punctuation">.</span><span class="token function">GET</span><span class="token punctuation">(</span><span class="token string">"/user/:id"</span><span class="token punctuation">,</span> <span class="token keyword">func</span><span class="token punctuation">(</span>context <span class="token operator">*</span>gin<span class="token punctuation">.</span>Context<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    id <span class="token operator">:=</span> context<span class="token punctuation">.</span><span class="token function">Param</span><span class="token punctuation">(</span><span class="token string">"id"</span><span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>id<span class="token punctuation">)</span>
    <span class="token keyword">if</span> id <span class="token operator">==</span> <span class="token string">"1"</span> <span class="token punctuation">&#123;</span>
        context<span class="token punctuation">.</span><span class="token function">JSON</span><span class="token punctuation">(</span><span class="token number">200</span><span class="token punctuation">,</span> gin<span class="token punctuation">.</span>H<span class="token punctuation">&#123;</span>
            <span class="token string">"code"</span><span class="token punctuation">:</span> <span class="token number">200</span><span class="token punctuation">,</span>
            <span class="token string">"msg"</span><span class="token punctuation">:</span> User<span class="token punctuation">&#123;</span>
                UserName<span class="token punctuation">:</span> <span class="token string">"dujie"</span><span class="token punctuation">,</span>
                Age<span class="token punctuation">:</span>      <span class="token number">32</span><span class="token punctuation">,</span>
                Phone<span class="token punctuation">:</span>    <span class="token string">"15811047166"</span><span class="token punctuation">,</span>
            <span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
        <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
        context<span class="token punctuation">.</span><span class="token function">JSON</span><span class="token punctuation">(</span><span class="token number">200</span><span class="token punctuation">,</span> gin<span class="token punctuation">.</span>H<span class="token punctuation">&#123;</span>
            <span class="token string">"code"</span><span class="token punctuation">:</span> <span class="token string">"404"</span><span class="token punctuation">,</span>
            <span class="token string">"msg"</span><span class="token punctuation">:</span>  <span class="token string">"无此用户！！！"</span><span class="token punctuation">,</span>
        <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span>

<span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>（4）、将请求参数绑定到结构体</strong></p>
<p>前面获取参数的方式都是逐个进行参数的读取，比较麻烦。Gin支持将请求参数自动绑定到一个结构体对象，这种方式支持GET&#x2F;POST请求，也支持HTTP请求体中内容为JSON或XML格式的参数。</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">type</span> User <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
    UserName <span class="token builtin">string</span> <span class="token string">`json:"userName" form:"username"`</span>
    Phone    <span class="token builtin">string</span> <span class="token string">`json:"phone" form:"phone"`</span>
    Age      <span class="token builtin">int</span>    <span class="token string">`json:"age" form:"age"`</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<table>
<thead>
<tr>
<th>标签</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>json:”userName”</td>
<td>数据为JSON格式，并且json字段名为userName</td>
</tr>
<tr>
<td>form:”phone”</td>
<td>表单参数名为phone</td>
</tr>
</tbody></table>
<p>模拟添加用户：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">r<span class="token punctuation">.</span><span class="token function">POST</span><span class="token punctuation">(</span><span class="token string">"/user/:id"</span><span class="token punctuation">,</span> <span class="token keyword">func</span><span class="token punctuation">(</span>context <span class="token operator">*</span>gin<span class="token punctuation">.</span>Context<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    u <span class="token operator">:=</span> User<span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
    <span class="token keyword">if</span> context<span class="token punctuation">.</span><span class="token function">ShouldBind</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>u<span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
        log<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>u<span class="token punctuation">.</span>UserName<span class="token punctuation">)</span>
        log<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>u<span class="token punctuation">.</span>Phone<span class="token punctuation">)</span>
        log<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>u<span class="token punctuation">.</span>Age<span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span>
    context<span class="token punctuation">.</span><span class="token function">JSON</span><span class="token punctuation">(</span><span class="token number">200</span><span class="token punctuation">,</span> gin<span class="token punctuation">.</span>H<span class="token punctuation">&#123;</span>
        <span class="token string">"code"</span><span class="token punctuation">:</span> http<span class="token punctuation">.</span>StatusOK<span class="token punctuation">,</span>
        <span class="token string">"msg"</span><span class="token punctuation">:</span>  u<span class="token punctuation">,</span>
    <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
    <span class="token comment">//context.String(200, "Success")</span>

<span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><code>context.ShouldBind(&amp;u) </code>用于将请求中的数据绑定到指定的结构体</p>
<h5 id="5、Gin生成HTTP请求响应"><a href="#5、Gin生成HTTP请求响应" class="headerlink" title="5、Gin生成HTTP请求响应"></a>5、Gin生成HTTP请求响应</h5><p>Gin支持以字符串、JSON、XML、文件等格式生成HTTP请求响应。gin.Context 上下文对象支持多种返回处理结果。</p>
<p><strong>（1）以字符串方式生成HTTP请求响应。</strong></p>
<p>通过String()方法生成字符串方式的HTTP请求响应。String()方法的定义如下：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// String writes the given string into the response body.</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>Context<span class="token punctuation">)</span> <span class="token function">String</span><span class="token punctuation">(</span>code <span class="token builtin">int</span><span class="token punctuation">,</span> format <span class="token builtin">string</span><span class="token punctuation">,</span> values <span class="token operator">...</span>any<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	c<span class="token punctuation">.</span><span class="token function">Render</span><span class="token punctuation">(</span>code<span class="token punctuation">,</span> render<span class="token punctuation">.</span>String<span class="token punctuation">&#123;</span>Format<span class="token punctuation">:</span> format<span class="token punctuation">,</span> Data<span class="token punctuation">:</span> values<span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>该方法使用示例如下：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">Handler</span><span class="token punctuation">(</span>c <span class="token operator">*</span>gin<span class="token punctuation">.</span>Context<span class="token punctuation">)</span><span class="token punctuation">&#123;</span>

        c<span class="token punctuation">.</span><span class="token function">String</span><span class="token punctuation">(</span><span class="token number">200</span><span class="token punctuation">,</span><span class="token string">"hello%s ,欢迎%s"</span><span class="token punctuation">,</span><span class="token string">"go"</span><span class="token punctuation">,</span><span class="token string">"dujie"</span><span class="token punctuation">)</span>

<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>（2）以JSON格式生成HTTP请求响应。</strong></p>
<p>实际开发API接口时，最常用的就是JSON</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">r<span class="token punctuation">.</span><span class="token function">POST</span><span class="token punctuation">(</span><span class="token string">"/user/:id"</span><span class="token punctuation">,</span> <span class="token keyword">func</span><span class="token punctuation">(</span>context <span class="token operator">*</span>gin<span class="token punctuation">.</span>Context<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    u <span class="token operator">:=</span> User<span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
    <span class="token keyword">if</span> context<span class="token punctuation">.</span><span class="token function">ShouldBind</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>u<span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
        log<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>u<span class="token punctuation">.</span>UserName<span class="token punctuation">)</span>
        log<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>u<span class="token punctuation">.</span>Phone<span class="token punctuation">)</span>
        log<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>u<span class="token punctuation">.</span>Age<span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span>
    context<span class="token punctuation">.</span><span class="token function">JSON</span><span class="token punctuation">(</span>http<span class="token punctuation">.</span>StatusOK<span class="token punctuation">,</span> gin<span class="token punctuation">.</span>H<span class="token punctuation">&#123;</span>
        <span class="token string">"code"</span><span class="token punctuation">:</span> http<span class="token punctuation">.</span>StatusOK<span class="token punctuation">,</span>
        <span class="token string">"msg"</span><span class="token punctuation">:</span>  u<span class="token punctuation">,</span>
    <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>（3）以XML格式生成HTTP请求响应。</strong></p>
<p>定义一个User结构体，默认结构体的名字就是XML的根节点名字。</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">type</span> User <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
    UserName <span class="token builtin">string</span> <span class="token string">`xml:"userName" form:"username"`</span>
    Phone    <span class="token builtin">string</span> <span class="token string">`xml:"phone" form:"phone"`</span>
    Age      <span class="token builtin">int</span>    <span class="token string">`xml:"age" form:"age"`</span>
<span class="token punctuation">&#125;</span>
    r<span class="token punctuation">.</span><span class="token function">GET</span><span class="token punctuation">(</span><span class="token string">"/user/:id"</span><span class="token punctuation">,</span> <span class="token keyword">func</span><span class="token punctuation">(</span>context <span class="token operator">*</span>gin<span class="token punctuation">.</span>Context<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        id <span class="token operator">:=</span> context<span class="token punctuation">.</span><span class="token function">Param</span><span class="token punctuation">(</span><span class="token string">"id"</span><span class="token punctuation">)</span>
        fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>id<span class="token punctuation">)</span>
        <span class="token keyword">if</span> id <span class="token operator">==</span> <span class="token string">"1"</span> <span class="token punctuation">&#123;</span>
            u <span class="token operator">:=</span> <span class="token operator">&amp;</span>User<span class="token punctuation">&#123;</span>
                UserName<span class="token punctuation">:</span> <span class="token string">"dujie"</span><span class="token punctuation">,</span>
                Age<span class="token punctuation">:</span>      <span class="token number">32</span><span class="token punctuation">,</span>
                Phone<span class="token punctuation">:</span>    <span class="token string">"15811047166"</span><span class="token punctuation">,</span>
            <span class="token punctuation">&#125;</span>
            context<span class="token punctuation">.</span><span class="token function">XML</span><span class="token punctuation">(</span><span class="token number">200</span><span class="token punctuation">,</span> u<span class="token punctuation">)</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>

        <span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><img src="/images/ximOXiVaTWYZnsZ9N_87_7NuNaY7VOlqtqA3kDWSJJ4.png" alt="image"></p>
<p><strong>（4）以文件格式生成HTTP请求响应。</strong></p>
<p>通过File() 方法直接返回本地文件，参数为本地文件地址</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span>（c <span class="token operator">*</span>gin<span class="token punctuation">.</span>Context<span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
<span class="token comment">// 通过File（）方法直接返回本地丈件’参数为本地丈件地址  ′</span>
      c<span class="token punctuation">.</span><span class="token function">File</span><span class="token punctuation">(</span><span class="token string">"/var/www/gin/test.jpg"</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>（5）设置HTTP响应头。</strong></p>
<p>Gin中提供了<code>Header()</code>方法来设置HTTP响应头。默认采用key&#x2F;value方式，支持设置多个Header</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">    r<span class="token punctuation">.</span><span class="token function">GET</span><span class="token punctuation">(</span><span class="token string">"/user/:id"</span><span class="token punctuation">,</span> <span class="token keyword">func</span><span class="token punctuation">(</span>context <span class="token operator">*</span>gin<span class="token punctuation">.</span>Context<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        id <span class="token operator">:=</span> context<span class="token punctuation">.</span><span class="token function">Param</span><span class="token punctuation">(</span><span class="token string">"id"</span><span class="token punctuation">)</span>
        fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>id<span class="token punctuation">)</span>
        context<span class="token punctuation">.</span><span class="token function">Header</span><span class="token punctuation">(</span><span class="token string">"Content-Type"</span><span class="token punctuation">,</span> <span class="token string">"application/json"</span><span class="token punctuation">)</span>
        context<span class="token punctuation">.</span><span class="token function">Header</span><span class="token punctuation">(</span><span class="token string">"site"</span><span class="token punctuation">,</span> <span class="token string">"dujie"</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><img src="/images/9ursxjNtKpQ9LIfDPeKTakw4TRCipaBkRqmaCp67lD0.png" alt="image"></p>
<p><strong>（6）Gin处理静态文件</strong></p>
<p>如果项目中包含JS、CSS、JPG之类的静态文件，下面的例子：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token comment">// 创建一个默认的路由引擎</span>
    r <span class="token operator">:=</span> gin<span class="token punctuation">.</span><span class="token function">Default</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    r<span class="token punctuation">.</span><span class="token function">Static</span><span class="token punctuation">(</span><span class="token string">"/assets"</span><span class="token punctuation">,</span><span class="token string">"/var/www/gin/assets"</span><span class="token punctuation">)</span>
    r<span class="token punctuation">.</span><span class="token function">StaticFile</span><span class="token punctuation">(</span><span class="token string">"/favicon.ico"</span><span class="token punctuation">,</span><span class="token string">"./static/favicon.ico"</span><span class="token punctuation">)</span>
    r<span class="token punctuation">.</span><span class="token function">Run</span><span class="token punctuation">(</span><span class="token string">":8080"</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>（7）Gin处理cookie</strong></p>
<p>Gin主要通过上下文对象提供的<code>SetCookie()</code> 和<code>Cookie()</code> 两个方法操作cookie，这两个函数都是对go语言<code>net/http</code>包中<code>http.SetCookie()</code>方法的重新封装，本质是一样</p>
<ol>
<li>设置cookie</li>
</ol>
<p>Gin使用SetCookie()方法设置cookie。</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// SetCookie adds a Set-Cookie header to the ResponseWriter's headers.</span>
<span class="token comment">// The provided cookie must have a valid Name. Invalid cookies may be</span>
<span class="token comment">// silently dropped.</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>Context<span class="token punctuation">)</span> <span class="token function">SetCookie</span><span class="token punctuation">(</span>name<span class="token punctuation">,</span> value <span class="token builtin">string</span><span class="token punctuation">,</span> maxAge <span class="token builtin">int</span><span class="token punctuation">,</span> path<span class="token punctuation">,</span> domain <span class="token builtin">string</span><span class="token punctuation">,</span> secure<span class="token punctuation">,</span> httpOnly <span class="token builtin">bool</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">if</span> path <span class="token operator">==</span> <span class="token string">""</span> <span class="token punctuation">&#123;</span>
		path <span class="token operator">=</span> <span class="token string">"/"</span>
	<span class="token punctuation">&#125;</span>
	http<span class="token punctuation">.</span><span class="token function">SetCookie</span><span class="token punctuation">(</span>c<span class="token punctuation">.</span>Writer<span class="token punctuation">,</span> <span class="token operator">&amp;</span>http<span class="token punctuation">.</span>Cookie<span class="token punctuation">&#123;</span>
		Name<span class="token punctuation">:</span>     name<span class="token punctuation">,</span>  <span class="token comment">// Cookie 的名称</span>
		Value<span class="token punctuation">:</span>    url<span class="token punctuation">.</span><span class="token function">QueryEscape</span><span class="token punctuation">(</span>value<span class="token punctuation">)</span><span class="token punctuation">,</span>  <span class="token comment">// Cookie的值</span>
		MaxAge<span class="token punctuation">:</span>   maxAge<span class="token punctuation">,</span> <span class="token comment">// 过期时间（秒）</span>
		Path<span class="token punctuation">:</span>     path<span class="token punctuation">,</span> <span class="token comment">// 路径</span>
		Domain<span class="token punctuation">:</span>   domain<span class="token punctuation">,</span> <span class="token comment">// 域</span>
		SameSite<span class="token punctuation">:</span> c<span class="token punctuation">.</span>sameSite<span class="token punctuation">,</span> 
		Secure<span class="token punctuation">:</span>   secure<span class="token punctuation">,</span> <span class="token comment">// 是否只允许HTTPs访问</span>
		HttpOnly<span class="token punctuation">:</span> httpOnly<span class="token punctuation">,</span> <span class="token comment">// 是否允许浏览器仅通过HTTP获取Cookie</span>
	<span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">r<span class="token punctuation">.</span><span class="token function">GET</span><span class="token punctuation">(</span><span class="token string">"/user/:id"</span><span class="token punctuation">,</span> <span class="token keyword">func</span><span class="token punctuation">(</span>context <span class="token operator">*</span>gin<span class="token punctuation">.</span>Context<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    context<span class="token punctuation">.</span><span class="token function">SetCookie</span><span class="token punctuation">(</span><span class="token string">"my_cookie"</span><span class="token punctuation">,</span> <span class="token string">"cookievalue"</span><span class="token punctuation">,</span> <span class="token number">3600</span><span class="token punctuation">,</span> <span class="token string">"/"</span><span class="token punctuation">,</span> <span class="token string">"localhost"</span><span class="token punctuation">,</span> <span class="token boolean">false</span><span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">)</span>
    id <span class="token operator">:=</span> context<span class="token punctuation">.</span><span class="token function">Param</span><span class="token punctuation">(</span><span class="token string">"id"</span><span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>id<span class="token punctuation">)</span>
    context<span class="token punctuation">.</span><span class="token function">Header</span><span class="token punctuation">(</span><span class="token string">"Content-Type"</span><span class="token punctuation">,</span> <span class="token string">"application/json"</span><span class="token punctuation">)</span>
    context<span class="token punctuation">.</span><span class="token function">Header</span><span class="token punctuation">(</span><span class="token string">"site"</span><span class="token punctuation">,</span> <span class="token string">"dujie"</span><span class="token punctuation">)</span>
    <span class="token keyword">if</span> id <span class="token operator">==</span> <span class="token string">"1"</span> <span class="token punctuation">&#123;</span>
        u <span class="token operator">:=</span> User<span class="token punctuation">&#123;</span>
            UserName<span class="token punctuation">:</span> <span class="token string">"dujie"</span><span class="token punctuation">,</span>
            Age<span class="token punctuation">:</span>      <span class="token number">32</span><span class="token punctuation">,</span>
            Phone<span class="token punctuation">:</span>    <span class="token string">"15811047166"</span><span class="token punctuation">,</span>
        <span class="token punctuation">&#125;</span>
        <span class="token comment">//context.XML(200, u)</span>
        context<span class="token punctuation">.</span><span class="token function">JSON</span><span class="token punctuation">(</span><span class="token number">200</span><span class="token punctuation">,</span> gin<span class="token punctuation">.</span>H<span class="token punctuation">&#123;</span>
            <span class="token string">"code"</span><span class="token punctuation">:</span> <span class="token number">200</span><span class="token punctuation">,</span>
            <span class="token string">"msg"</span><span class="token punctuation">:</span>  u<span class="token punctuation">,</span>
        <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
        context<span class="token punctuation">.</span><span class="token function">JSON</span><span class="token punctuation">(</span><span class="token number">200</span><span class="token punctuation">,</span> gin<span class="token punctuation">.</span>H<span class="token punctuation">&#123;</span>
            <span class="token string">"code"</span><span class="token punctuation">:</span> <span class="token string">"404"</span><span class="token punctuation">,</span>
            <span class="token string">"msg"</span><span class="token punctuation">:</span>  <span class="token string">"无此用户！！！"</span><span class="token punctuation">,</span>
        <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span>

<span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<p><img src="/images/cGczYh95uVn_E_XRJd719AQyRgUMRg69MAIwRrYI2xY.png" alt="image"></p>
<ol start="2">
<li>读取Cookie</li>
</ol>
<p>Gin使用Cookie() 方法读取cookie</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    r <span class="token operator">:=</span> gin<span class="token punctuation">.</span><span class="token function">Default</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    r<span class="token punctuation">.</span><span class="token function">GET</span><span class="token punctuation">(</span><span class="token string">"/user/:id"</span><span class="token punctuation">,</span> <span class="token keyword">func</span><span class="token punctuation">(</span>context <span class="token operator">*</span>gin<span class="token punctuation">.</span>Context<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token comment">//context.SetCookie("cookie", "value", 3600, "/", "127.0.0.1", false, true)</span>
        cookie<span class="token punctuation">,</span> err <span class="token operator">:=</span> context<span class="token punctuation">.</span><span class="token function">Cookie</span><span class="token punctuation">(</span><span class="token string">"cookie"</span><span class="token punctuation">)</span>
        <span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
            log<span class="token punctuation">.</span><span class="token function">Panicln</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
        <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="3">
<li>删除Cookie</li>
</ol>
<p>将SetCookie() 方法的MaxAge参数设置为-1，就可以删除cookie</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">context<span class="token punctuation">.</span><span class="token function">SetCookie</span><span class="token punctuation">(</span><span class="token string">"cookie"</span><span class="token punctuation">,</span> <span class="token string">"value"</span><span class="token punctuation">,</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token string">"/"</span><span class="token punctuation">,</span> <span class="token string">"127.0.0.1"</span><span class="token punctuation">,</span> <span class="token boolean">false</span><span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">)</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p><strong>（8）Gin文件上传</strong></p>
<p>Gin使用<code>SaveUploadFile()</code> 方法实现文件上传</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    r <span class="token operator">:=</span> gin<span class="token punctuation">.</span><span class="token function">Default</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    r<span class="token punctuation">.</span>MaxMultipartMemory <span class="token operator">=</span> <span class="token number">64</span> <span class="token operator">&lt;&lt;</span><span class="token number">20</span>
    r<span class="token punctuation">.</span><span class="token function">POST</span><span class="token punctuation">(</span><span class="token string">"/upload"</span><span class="token punctuation">,</span> <span class="token keyword">func</span><span class="token punctuation">(</span>context <span class="token operator">*</span>gin<span class="token punctuation">.</span>Context<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token comment">// file 是表单字段名字</span>
        file<span class="token punctuation">,</span><span class="token boolean">_</span> <span class="token operator">:=</span> context<span class="token punctuation">.</span><span class="token function">FormFile</span><span class="token punctuation">(</span><span class="token string">"file"</span><span class="token punctuation">)</span>
        <span class="token comment">// 打印上传的文件名</span>
        log<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>file<span class="token punctuation">.</span>Filename<span class="token punctuation">)</span>
        <span class="token comment">// 将上传的文件保存到./dujie.jpg中</span>
        context<span class="token punctuation">.</span><span class="token function">SaveUploadedFile</span><span class="token punctuation">(</span>file<span class="token punctuation">,</span><span class="token string">"./dujie.jpg"</span><span class="token punctuation">)</span>
        context<span class="token punctuation">.</span><span class="token function">String</span><span class="token punctuation">(</span><span class="token number">200</span><span class="token punctuation">,</span>fmt<span class="token punctuation">.</span><span class="token function">Sprintf</span><span class="token punctuation">(</span><span class="token string">"'%s' uploaded!"</span><span class="token punctuation">,</span>file<span class="token punctuation">.</span>Filename<span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
    r<span class="token punctuation">.</span><span class="token function">Run</span><span class="token punctuation">(</span><span class="token string">":8090"</span><span class="token punctuation">)</span>

<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>（9）Gin中间件</strong></p>
<p>Gin中，中间件(Middleware)是指可以拦截HTTP请求——响应生命周期的特殊函数。在请求——响应生命周期中可以注册多个中间件。每个中间件执行不同的功能，一个中间件执行完，才轮到下一个中间件执行，中间件常用的应用场景如下：</p>
<ul>
<li>请求限速</li>
<li>API接口签名处理</li>
<li>权限校验</li>
<li>统一错误处理</li>
</ul>
<p>如果想拦截所有请求，则可以开发一个中间件函数来实现。Gin支持设置全局中间件和针对路由分组的中间件。在设置全局中间件后，会拦截所有请求。通过分组路由设置的中间件，仅对这个分组下的路由起作用</p>
<p><strong>（9.1）使用中间件</strong></p>
<p>Gin中使用<code>Use()</code>方法来使用中间件</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    r <span class="token operator">:=</span> gin<span class="token punctuation">.</span><span class="token function">Default</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token comment">// 通过Use()方法设置中间件</span>
    <span class="token comment">// 设置日志中间件，主要用于打印请求日志</span>
    r<span class="token punctuation">.</span><span class="token function">Use</span><span class="token punctuation">(</span>gin<span class="token punctuation">.</span><span class="token function">Logger</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token comment">// 设置Recovery中间件，主要用于拦截panic错误，不至于导致程序崩溃</span>
    r<span class="token punctuation">.</span><span class="token function">Use</span><span class="token punctuation">(</span>gin<span class="token punctuation">.</span><span class="token function">Recovery</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    r<span class="token punctuation">.</span><span class="token function">GET</span><span class="token punctuation">(</span><span class="token string">"/user/:id"</span><span class="token punctuation">,</span> <span class="token keyword">func</span><span class="token punctuation">(</span>context <span class="token operator">*</span>gin<span class="token punctuation">.</span>Context<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        context<span class="token punctuation">.</span><span class="token function">JSON</span><span class="token punctuation">(</span><span class="token number">200</span><span class="token punctuation">,</span> gin<span class="token punctuation">.</span>H<span class="token punctuation">&#123;</span>
            <span class="token string">"code"</span><span class="token punctuation">:</span> <span class="token number">200</span><span class="token punctuation">,</span>
            <span class="token string">"msg"</span><span class="token punctuation">:</span>  <span class="token string">"成功"</span><span class="token punctuation">,</span>
        <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
    r<span class="token punctuation">.</span><span class="token function">Run</span><span class="token punctuation">(</span><span class="token string">":8090"</span><span class="token punctuation">)</span>

<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>（9.2）自定义中间件</strong></p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">Logger</span><span class="token punctuation">(</span><span class="token punctuation">)</span> gin<span class="token punctuation">.</span>HandlerFunc <span class="token punctuation">&#123;</span>
    <span class="token keyword">return</span> <span class="token keyword">func</span><span class="token punctuation">(</span>context <span class="token operator">*</span>gin<span class="token punctuation">.</span>Context<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        t <span class="token operator">:=</span> time<span class="token punctuation">.</span><span class="token function">Now</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
        <span class="token comment">// 可以通过上下文对象，设置一些依附在上下文对象里面的键值数据</span>
        context<span class="token punctuation">.</span><span class="token function">Set</span><span class="token punctuation">(</span><span class="token string">"example"</span><span class="token punctuation">,</span> <span class="token string">"这是一个中间件数据"</span><span class="token punctuation">)</span>
        <span class="token comment">// 在这里处理请求到达处理器函数之前的逻辑</span>

        <span class="token comment">// 调用下一个中间件，或者处理器的处理函数，具体得看注册了多少个中间件</span>
        context<span class="token punctuation">.</span><span class="token function">Next</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
        <span class="token comment">// 在这里可以处理返给客户端之前的响应逻辑</span>
        latency <span class="token operator">:=</span> time<span class="token punctuation">.</span><span class="token function">Since</span><span class="token punctuation">(</span>t<span class="token punctuation">)</span>
        log<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>latency<span class="token punctuation">)</span>

        <span class="token comment">// 例如，查询请求状态码</span>
        status <span class="token operator">:=</span> context<span class="token punctuation">.</span>Writer<span class="token punctuation">.</span><span class="token function">Status</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
        log<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>status<span class="token punctuation">)</span>

    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    r <span class="token operator">:=</span> gin<span class="token punctuation">.</span><span class="token function">Default</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token comment">// 注册上面自定义的日志中间件</span>
    r<span class="token punctuation">.</span><span class="token function">Use</span><span class="token punctuation">(</span><span class="token function">Logger</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    r<span class="token punctuation">.</span><span class="token function">GET</span><span class="token punctuation">(</span><span class="token string">"/hello"</span><span class="token punctuation">,</span> <span class="token keyword">func</span><span class="token punctuation">(</span>context <span class="token operator">*</span>gin<span class="token punctuation">.</span>Context<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token comment">// 获取日志中间件中注入的键值数据，接口断言是否是string类型</span>
        example <span class="token operator">:=</span> context<span class="token punctuation">.</span><span class="token function">MustGet</span><span class="token punctuation">(</span><span class="token string">"example"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token punctuation">(</span><span class="token builtin">string</span><span class="token punctuation">)</span>
        log<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>example<span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
    r<span class="token punctuation">.</span><span class="token function">Run</span><span class="token punctuation">(</span><span class="token string">":8090"</span><span class="token punctuation">)</span>

<span class="token punctuation">&#125;</span>
<span class="token comment">// 运行访问后输出</span>
<span class="token punctuation">[</span>GIN<span class="token operator">-</span>debug<span class="token punctuation">]</span> GET    <span class="token operator">/</span>hello                    <span class="token operator">--</span><span class="token operator">></span> main<span class="token punctuation">.</span>main<span class="token punctuation">.</span>func1 <span class="token punctuation">(</span><span class="token number">4</span> handlers<span class="token punctuation">)</span>
<span class="token punctuation">[</span>GIN<span class="token operator">-</span>debug<span class="token punctuation">]</span> <span class="token punctuation">[</span>WARNING<span class="token punctuation">]</span> You trusted all proxies<span class="token punctuation">,</span> this is NOT safe<span class="token punctuation">.</span> We recommend you to set a value<span class="token punctuation">.</span>
Please check https<span class="token punctuation">:</span><span class="token operator">/</span><span class="token operator">/</span>pkg<span class="token punctuation">.</span><span class="token keyword">go</span><span class="token punctuation">.</span>dev<span class="token operator">/</span>github<span class="token punctuation">.</span>com<span class="token operator">/</span>gin<span class="token operator">-</span>gonic<span class="token operator">/</span>gin#readme<span class="token operator">-</span>don<span class="token operator">-</span>t<span class="token operator">-</span>trust<span class="token operator">-</span>all<span class="token operator">-</span>proxies <span class="token keyword">for</span> details<span class="token punctuation">.</span>
<span class="token punctuation">[</span>GIN<span class="token operator">-</span>debug<span class="token punctuation">]</span> Listening and serving HTTP on <span class="token punctuation">:</span><span class="token number">8090</span>
<span class="token number">2023</span><span class="token operator">/</span><span class="token number">08</span><span class="token operator">/</span><span class="token number">30</span> <span class="token number">09</span><span class="token punctuation">:</span><span class="token number">07</span><span class="token punctuation">:</span><span class="token number">53</span> 这是一个中间件数据
<span class="token number">2023</span><span class="token operator">/</span><span class="token number">08</span><span class="token operator">/</span><span class="token number">30</span> <span class="token number">09</span><span class="token punctuation">:</span><span class="token number">07</span><span class="token punctuation">:</span><span class="token number">53</span> <span class="token number">256.417</span>µs
<span class="token number">2023</span><span class="token operator">/</span><span class="token number">08</span><span class="token operator">/</span><span class="token number">30</span> <span class="token number">09</span><span class="token punctuation">:</span><span class="token number">07</span><span class="token punctuation">:</span><span class="token number">53</span> <span class="token number">200</span>
<span class="token punctuation">[</span>GIN<span class="token punctuation">]</span> <span class="token number">2023</span><span class="token operator">/</span><span class="token number">08</span><span class="token operator">/</span><span class="token number">30</span> <span class="token operator">-</span> <span class="token number">09</span><span class="token punctuation">:</span><span class="token number">07</span><span class="token punctuation">:</span><span class="token number">53</span> <span class="token operator">|</span> <span class="token number">200</span> <span class="token operator">|</span>     <span class="token number">369.125</span>µs <span class="token operator">|</span>       <span class="token number">127.0</span><span class="token number">.0</span><span class="token number">.1</span> <span class="token operator">|</span> GET      <span class="token string">"/hello"</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>（10）Gin处理session</strong></p>
<p>在Gin中，依赖”github.com&#x2F;gin-contrib&#x2F;sessions”包中的中间件处理session。该包中的中间件支持cookie、MemStore、Redis、Memcached、Mongodb引擎。</p>
<p>1、安装</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">go</span> get <span class="token operator">-</span>u github<span class="token punctuation">.</span>com<span class="token operator">/</span>gin<span class="token operator">-</span>contrib<span class="token operator">/</span>sessions
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>2、用法示例</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    r <span class="token operator">:=</span> gin<span class="token punctuation">.</span><span class="token function">Default</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token comment">// 创建基于cookie的存储引擎，password123456参数是用于加密的秘钥</span>
    store <span class="token operator">:=</span> cookie<span class="token punctuation">.</span><span class="token function">NewStore</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token function">byte</span><span class="token punctuation">(</span><span class="token string">"password123456"</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token comment">// 设置session中间件，参数my_session 指的是session的名字，也是cookie的名字</span>
    <span class="token comment">// store是前面创建的存储引擎，可以将其替换成其他存储引擎，如Redis等</span>
    r<span class="token punctuation">.</span><span class="token function">Use</span><span class="token punctuation">(</span>sessions<span class="token punctuation">.</span><span class="token function">Sessions</span><span class="token punctuation">(</span><span class="token string">"my_session"</span><span class="token punctuation">,</span> store<span class="token punctuation">)</span><span class="token punctuation">)</span>
    r<span class="token punctuation">.</span><span class="token function">GET</span><span class="token punctuation">(</span><span class="token string">"/hello"</span><span class="token punctuation">,</span> <span class="token keyword">func</span><span class="token punctuation">(</span>context <span class="token operator">*</span>gin<span class="token punctuation">.</span>Context<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token comment">// 初始化session对象</span>
        session <span class="token operator">:=</span> sessions<span class="token punctuation">.</span><span class="token function">Default</span><span class="token punctuation">(</span>context<span class="token punctuation">)</span>
        <span class="token comment">// 通过session Get()函数读取session值</span>
        <span class="token comment">// session 是键值对格式数据，因此需要通过key查询数据</span>
        <span class="token keyword">if</span> session<span class="token punctuation">.</span><span class="token function">Get</span><span class="token punctuation">(</span><span class="token string">"hello"</span><span class="token punctuation">)</span> <span class="token operator">!=</span> <span class="token string">"world"</span> <span class="token punctuation">&#123;</span>
            <span class="token comment">// 设置session数据</span>
            session<span class="token punctuation">.</span><span class="token function">Set</span><span class="token punctuation">(</span><span class="token string">"hello"</span><span class="token punctuation">,</span> <span class="token string">"world"</span><span class="token punctuation">)</span>
            <span class="token comment">// 删除session数据</span>
            session<span class="token punctuation">.</span><span class="token function">Delete</span><span class="token punctuation">(</span><span class="token string">"dujie"</span><span class="token punctuation">)</span>
            <span class="token comment">// 保存session数据</span>
            session<span class="token punctuation">.</span><span class="token function">Save</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
            <span class="token comment">// 删除整个session</span>
            <span class="token comment">// session.Clear()</span>
        <span class="token punctuation">&#125;</span>
        context<span class="token punctuation">.</span><span class="token function">JSON</span><span class="token punctuation">(</span><span class="token number">200</span><span class="token punctuation">,</span> gin<span class="token punctuation">.</span>H<span class="token punctuation">&#123;</span>
            <span class="token string">"hello"</span><span class="token punctuation">:</span> session<span class="token punctuation">.</span><span class="token function">Get</span><span class="token punctuation">(</span><span class="token string">"hello"</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
        <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
    <span class="token comment">// 获取session</span>
    r<span class="token punctuation">.</span><span class="token function">GET</span><span class="token punctuation">(</span><span class="token string">"/session"</span><span class="token punctuation">,</span> Handler<span class="token punctuation">)</span>

    r<span class="token punctuation">.</span><span class="token function">Run</span><span class="token punctuation">(</span><span class="token string">":8090"</span><span class="token punctuation">)</span>

<span class="token punctuation">&#125;</span>
<span class="token comment">// 获取session的handler函数</span>
<span class="token keyword">func</span> <span class="token function">Handler</span><span class="token punctuation">(</span>c <span class="token operator">*</span>gin<span class="token punctuation">.</span>Context<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    data<span class="token punctuation">,</span> err <span class="token operator">:=</span> c<span class="token punctuation">.</span><span class="token function">Cookie</span><span class="token punctuation">(</span><span class="token string">"my_session"</span><span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
    <span class="token keyword">if</span> err <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
        c<span class="token punctuation">.</span><span class="token function">String</span><span class="token punctuation">(</span><span class="token number">200</span><span class="token punctuation">,</span> data<span class="token punctuation">)</span>
        <span class="token keyword">return</span>
    <span class="token punctuation">&#125;</span>
    c<span class="token punctuation">.</span><span class="token function">String</span><span class="token punctuation">(</span><span class="token number">200</span><span class="token punctuation">,</span> <span class="token string">"not found"</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><img src="/images/PdOQSGRA-04_7y1ZYpow_iacKReUL_XvlN8eZfqWmCE.png" alt="image"></p>
<p>3、基于Redis存储引擎的session</p>
<p>如果想将session数据保存到Redis中，则只要将session的存储引擎改成Redis即可</p>
<p>安装Gin的Redis存储引擎包</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">go</span> get <span class="token operator">-</span>u github<span class="token punctuation">.</span>com<span class="token operator">/</span>gin<span class="token operator">-</span>contrib<span class="token operator">/</span>sessions<span class="token operator">/</span>redis
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>基于Redis存储引擎示例</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    r <span class="token operator">:=</span> gin<span class="token punctuation">.</span><span class="token function">Default</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token comment">//store := cookie.NewStore([]byte("password123456"))</span>
    <span class="token comment">// 初始化基于redis的存储引擎</span>
    store<span class="token punctuation">,</span> err <span class="token operator">:=</span> redis<span class="token punctuation">.</span><span class="token function">NewStore</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">,</span> <span class="token string">"tcp"</span><span class="token punctuation">,</span> <span class="token string">"localhost:6379"</span><span class="token punctuation">,</span> <span class="token string">""</span><span class="token punctuation">,</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token function">byte</span><span class="token punctuation">(</span><span class="token string">"password"</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
        log<span class="token punctuation">.</span><span class="token function">Panicln</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span>
    r<span class="token punctuation">.</span><span class="token function">Use</span><span class="token punctuation">(</span>sessions<span class="token punctuation">.</span><span class="token function">Sessions</span><span class="token punctuation">(</span><span class="token string">"my_session"</span><span class="token punctuation">,</span> store<span class="token punctuation">)</span><span class="token punctuation">)</span>
    r<span class="token punctuation">.</span><span class="token function">GET</span><span class="token punctuation">(</span><span class="token string">"/hello"</span><span class="token punctuation">,</span> <span class="token keyword">func</span><span class="token punctuation">(</span>context <span class="token operator">*</span>gin<span class="token punctuation">.</span>Context<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        session <span class="token operator">:=</span> sessions<span class="token punctuation">.</span><span class="token function">Default</span><span class="token punctuation">(</span>context<span class="token punctuation">)</span>
        <span class="token keyword">var</span> count <span class="token builtin">int</span>
        v <span class="token operator">:=</span> session<span class="token punctuation">.</span><span class="token function">Get</span><span class="token punctuation">(</span><span class="token string">"count"</span><span class="token punctuation">)</span>
        <span class="token keyword">if</span> v <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
            count <span class="token operator">=</span> <span class="token number">0</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
            count <span class="token operator">=</span> v<span class="token punctuation">.</span><span class="token punctuation">(</span><span class="token builtin">int</span><span class="token punctuation">)</span>
            count<span class="token operator">++</span>
        <span class="token punctuation">&#125;</span>
        session<span class="token punctuation">.</span><span class="token function">Set</span><span class="token punctuation">(</span><span class="token string">"count"</span><span class="token punctuation">,</span> count<span class="token punctuation">)</span>
        session<span class="token punctuation">.</span><span class="token function">Save</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
        context<span class="token punctuation">.</span><span class="token function">JSON</span><span class="token punctuation">(</span><span class="token number">200</span><span class="token punctuation">,</span> gin<span class="token punctuation">.</span>H<span class="token punctuation">&#123;</span>
            <span class="token string">"count"</span><span class="token punctuation">:</span> count<span class="token punctuation">,</span>
        <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
    r<span class="token punctuation">.</span><span class="token function">GET</span><span class="token punctuation">(</span><span class="token string">"/session"</span><span class="token punctuation">,</span> Handler<span class="token punctuation">)</span>
    r<span class="token punctuation">.</span><span class="token function">Run</span><span class="token punctuation">(</span><span class="token string">":8090"</span><span class="token punctuation">)</span>

<span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token function">Handler</span><span class="token punctuation">(</span>c <span class="token operator">*</span>gin<span class="token punctuation">.</span>Context<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token comment">// 上下文中获取session</span>
    session <span class="token operator">:=</span> sessions<span class="token punctuation">.</span><span class="token function">Default</span><span class="token punctuation">(</span>c<span class="token punctuation">)</span>
    count <span class="token operator">:=</span> session<span class="token punctuation">.</span><span class="token function">Get</span><span class="token punctuation">(</span><span class="token string">"count"</span><span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"————————"</span><span class="token punctuation">,</span> count<span class="token punctuation">)</span>
    <span class="token keyword">if</span> count <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
        c<span class="token punctuation">.</span><span class="token function">JSON</span><span class="token punctuation">(</span><span class="token number">200</span><span class="token punctuation">,</span> gin<span class="token punctuation">.</span>H<span class="token punctuation">&#123;</span>
            <span class="token string">"count"</span><span class="token punctuation">:</span> count<span class="token punctuation">,</span>
        <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
        <span class="token keyword">return</span>
    <span class="token punctuation">&#125;</span>
    c<span class="token punctuation">.</span><span class="token function">String</span><span class="token punctuation">(</span><span class="token number">200</span><span class="token punctuation">,</span> <span class="token string">"not found"</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>




































































</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="http://dycloudnavite.love">J.</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://dycloudnavite.love/2023/06/23/Gin%E6%A1%86%E6%9E%B6/">http://dycloudnavite.love/2023/06/23/Gin%E6%A1%86%E6%9E%B6/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://dycloudnavite.love" target="_blank">J.のblog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/dujie5416/tags/%E4%BA%91%E5%8E%9F%E7%94%9F/">云原生</a><a class="post-meta__tags" href="/dujie5416/tags/golang/">golang</a></div><div class="post_share"><div class="addthis_inline_share_toolbox"></div><script src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-5d034d84b42927bf" async="async"></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/dujie5416/img/wechat.jpg" target="_blank"><img class="post-qr-code-img" src="/dujie5416/img/wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/dujie5416/img/alipay.jpg" target="_blank"><img class="post-qr-code-img" src="/dujie5416/img/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/dujie5416/2023/06/27/%E5%9F%BA%E4%BA%8EIOC%E8%A7%A3%E5%86%B3%E5%AF%B9%E8%B1%A1%E4%BE%9D%E8%B5%96%E9%97%AE%E9%A2%98/"><img class="prev-cover" src="/dujie5416/img/golang.png" onerror="onerror=null;src='/dujie5416/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">基于IOC解决对象依赖问题</div></div></a></div><div class="next-post pull-right"><a href="/dujie5416/2023/06/04/ServeMux%E3%80%81httprouter/"><img class="next-cover" src="/dujie5416/img/golang.png" onerror="onerror=null;src='/dujie5416/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">ServeMux、httprouter</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/dujie5416/2023/05/20/Channel%E9%80%9A%E9%81%93/" title="Channel通道"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-05-20</div><div class="title">Channel通道</div></div></a></div><div><a href="/dujie5416/2023/05/06/Golang%E4%B8%AD%E7%9A%84GORM/" title="Golang GORM使用"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-05-06</div><div class="title">Golang GORM使用</div></div></a></div><div><a href="/dujie5416/2023/05/15/Golang%E5%8D%8F%E7%A8%8B/" title="Golang协程"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-05-15</div><div class="title">Golang协程</div></div></a></div><div><a href="/dujie5416/2023/04/17/Golang%E5%8F%98%E9%87%8F%E9%80%83%E9%80%B8%E2%80%94%E2%80%94%E5%A0%86%E3%80%81%E6%A0%88/" title="Golang变量逃逸————堆、栈"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-04-17</div><div class="title">Golang变量逃逸————堆、栈</div></div></a></div><div><a href="/dujie5416/2023/02/13/Golang%E5%AD%97%E7%AC%A6%E4%B8%B2string/" title="Golang字符串"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-02-13</div><div class="title">Golang字符串</div></div></a></div><div><a href="/dujie5416/2023/04/15/Golang%20List/" title="Golang List"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-04-15</div><div class="title">Golang List</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="lv-container" data-id="city" data-uid="MTAyMC81Njk5OS8zMzQ2Mw=="></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/dujie5416/img/touxiang.png" onerror="this.onerror=null;this.src='/dujie5416/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">J.</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/dujie5416/archives/"><div class="headline">文章</div><div class="length-num">73</div></a><a href="/dujie5416/tags/"><div class="headline">标签</div><div class="length-num">17</div></a><a href="/dujie5416/categories/"><div class="headline">分类</div><div class="length-num">11</div></a></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Gin%E6%A1%86%E6%9E%B6"><span class="toc-number">1.</span> <span class="toc-text">Gin框架</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%80%E3%80%81Gin%E6%A1%86%E6%9E%B6%E4%BD%BF%E7%94%A8"><span class="toc-number">1.0.1.</span> <span class="toc-text">一、Gin框架使用</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#1%E3%80%81Gin%E6%A1%86%E6%9E%B6%E7%AE%80%E4%BB%8B"><span class="toc-number">1.0.1.0.1.</span> <span class="toc-text">1、Gin框架简介</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#2%E3%80%81Gin%E6%A1%86%E6%9E%B6%E5%AE%89%E8%A3%85%E4%B8%8E%E7%A4%BA%E4%BE%8B"><span class="toc-number">1.0.1.0.2.</span> <span class="toc-text">2、Gin框架安装与示例</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#3%E3%80%81Gin%E8%B7%AF%E7%94%B1%E5%92%8C%E6%8E%A7%E5%88%B6%E5%99%A8"><span class="toc-number">1.0.1.0.3.</span> <span class="toc-text">3、Gin路由和控制器</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#4%E3%80%81Gin%E5%A4%84%E7%90%86%E8%AF%B7%E6%B1%82%E5%8F%82%E6%95%B0"><span class="toc-number">1.0.1.0.4.</span> <span class="toc-text">4、Gin处理请求参数</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#5%E3%80%81Gin%E7%94%9F%E6%88%90HTTP%E8%AF%B7%E6%B1%82%E5%93%8D%E5%BA%94"><span class="toc-number">1.0.1.0.5.</span> <span class="toc-text">5、Gin生成HTTP请求响应</span></a></li></ol></li></ol></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/07/29/%E6%A0%B9%E6%8D%AErouter%E6%98%BE%E7%A4%BA%E5%B7%A6%E4%BE%A7%E8%8F%9C%E5%8D%95%E6%A0%8F%E9%9A%90%E8%97%8F%E6%9F%90%E4%B8%AA%E8%8F%9C%E5%8D%95%E9%80%89%E9%A1%B9/" title="vue3左侧菜单隐藏某选项"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="vue3左侧菜单隐藏某选项"/></a><div class="content"><a class="title" href="/dujie5416/2023/07/29/%E6%A0%B9%E6%8D%AErouter%E6%98%BE%E7%A4%BA%E5%B7%A6%E4%BE%A7%E8%8F%9C%E5%8D%95%E6%A0%8F%E9%9A%90%E8%97%8F%E6%9F%90%E4%B8%AA%E8%8F%9C%E5%8D%95%E9%80%89%E9%A1%B9/" title="vue3左侧菜单隐藏某选项">vue3左侧菜单隐藏某选项</a><time datetime="2023-07-29T06:32:00.000Z" title="发表于 2023-07-29 14:32:00">2023-07-29</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/07/13/Vue%E7%8A%B6%E6%80%81%E7%AE%A1%E7%90%86/" title="Vue状态管理"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="Vue状态管理"/></a><div class="content"><a class="title" href="/dujie5416/2023/07/13/Vue%E7%8A%B6%E6%80%81%E7%AE%A1%E7%90%86/" title="Vue状态管理">Vue状态管理</a><time datetime="2023-07-13T09:29:00.000Z" title="发表于 2023-07-13 17:29:00">2023-07-13</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/06/27/%E5%9F%BA%E4%BA%8EIOC%E8%A7%A3%E5%86%B3%E5%AF%B9%E8%B1%A1%E4%BE%9D%E8%B5%96%E9%97%AE%E9%A2%98/" title="基于IOC解决对象依赖问题"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="基于IOC解决对象依赖问题"/></a><div class="content"><a class="title" href="/dujie5416/2023/06/27/%E5%9F%BA%E4%BA%8EIOC%E8%A7%A3%E5%86%B3%E5%AF%B9%E8%B1%A1%E4%BE%9D%E8%B5%96%E9%97%AE%E9%A2%98/" title="基于IOC解决对象依赖问题">基于IOC解决对象依赖问题</a><time datetime="2023-06-27T03:32:00.000Z" title="发表于 2023-06-27 11:32:00">2023-06-27</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/06/23/Gin%E6%A1%86%E6%9E%B6/" title="Gin框架"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="Gin框架"/></a><div class="content"><a class="title" href="/dujie5416/2023/06/23/Gin%E6%A1%86%E6%9E%B6/" title="Gin框架">Gin框架</a><time datetime="2023-06-23T06:32:00.000Z" title="发表于 2023-06-23 14:32:00">2023-06-23</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/06/04/ServeMux%E3%80%81httprouter/" title="ServeMux、httprouter"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="ServeMux、httprouter"/></a><div class="content"><a class="title" href="/dujie5416/2023/06/04/ServeMux%E3%80%81httprouter/" title="ServeMux、httprouter">ServeMux、httprouter</a><time datetime="2023-06-04T03:32:00.000Z" title="发表于 2023-06-04 11:32:00">2023-06-04</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('/dujie5416/img/longzhu.png')"><div id="footer-wrap"><div class="copyright">&copy;2019 - 2024  <i id="heartbeat" class="fa fas fa-heartbeat"></i> J.</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a><a href="http://beian.miit.gov.cn/"  style="color:#f72b07" target="_blank">京ICP备2022023567号</a></div></div><link rel="stylesheet" href="https://fastly.jsdelivr.net/gh/HCLonely/images@master/others/heartbeat.min.css"></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="algolia-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="search-wrap"><div id="algolia-search-input"></div><hr/><div id="algolia-search-results"><div id="algolia-hits"></div><div id="algolia-pagination"></div><div id="algolia-info"><div class="algolia-stats"></div><div class="algolia-poweredBy"></div></div></div></div></div><div id="search-mask"></div></div><div id="rightMenu"><div class="rightMenu-group rightMenu-small"><div class="rightMenu-item" id="menu-backward"><i class="fa-solid fa-arrow-left"></i></div><div class="rightMenu-item" id="menu-forward"><i class="fa-solid fa-arrow-right"></i></div><div class="rightMenu-item" id="menu-refresh"><i class="fa-solid fa-arrow-rotate-right"></i></div><div class="rightMenu-item" id="menu-home"><i class="fa-solid fa-house"></i></div></div><div class="rightMenu-group rightMenu-line rightMenuOther"><a class="rightMenu-item menu-link" href="/archives/"><i class="fa-solid fa-archive"></i><span>文章归档</span></a><a class="rightMenu-item menu-link" href="/categories/"><i class="fa-solid fa-folder-open"></i><span>文章分类</span></a><a class="rightMenu-item menu-link" href="/tags/"><i class="fa-solid fa-tags"></i><span>文章标签</span></a></div><div class="rightMenu-group rightMenu-line rightMenuNormal"><a class="rightMenu-item menu-link" id="menu-radompage" href="/random/index.html"><i class="fa-solid fa-shoe-prints"></i><span>随便逛逛</span></a><div class="rightMenu-item" id="menu-translate"><i class="fa-solid fa-earth-asia"></i><span>繁简切换</span></div><div class="rightMenu-item" id="menu-darkmode"><i class="fa-solid fa-moon"></i><span>切换模式</span></div></div></div><div id="rightmenu-mask"></div><div><script src="/dujie5416/js/utils.js"></script><script src="/dujie5416/js/main.js"></script><script src="/dujie5416/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/algoliasearch/dist/algoliasearch-lite.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instantsearch.js/dist/instantsearch.production.min.js"></script><script src="/dujie5416/js/search/algolia.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>function loadLivere () {
  if (typeof LivereTower === 'object') {
    window.LivereTower.init()
  }
  else {
    (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
    })(document, 'script');
  }
}

if ('Livere' === 'Livere' || !false) {
  if (false) btf.loadComment(document.getElementById('lv-container'), loadLivere)
  else loadLivere()
}
else {
  function loadOtherComment () {
    loadLivere()
  }
}</script></div><script defer src="https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js"></script><script data-pjax defer src="https://npm.elemecdn.com/tzy-blog/lib/js/theme/chocolate.js"></script><canvas id="universe"></canvas><script defer src="/js/universe.js"></script><script defer data-pjax src="/js/rightMenu.js"></script><div class="aplayer no-destroy" data-id="7427714271" data-server="netease" data-type="playlist" data-fixed="true" data-mini="true" data-listFolded="false" data-order="random" data-lrctype="1" data-preload="none" data-autoplay="true" muted></div><script id="click-show-text" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/click-show-text.min.js" data-mobile="false" data-text="I,LOVE,YOU" data-fontsize="15px" data-random="false" async="async"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/metingjs/dist/Meting.min.js"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = ["meta[property=\"og:image\"]","meta[property=\"og:title\"]","meta[property=\"og:url\"]","head > title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show",".js-pjax"]

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.tocScrollFn && window.removeEventListener('scroll', window.tocScrollFn)
  window.scrollCollect && window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  document.getElementById('rightside').style.cssText = "opacity: ''; transform: ''"
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

  typeof disqusjs === 'object' && disqusjs.destroy()
})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><!-- hexo injector body_end start --><script data-pjax>
  function butterfly_clock_anzhiyu_injector_config(){
    var parent_div_git = document.getElementsByClassName('sticky_layout')[0];
    var item_html = '<div class="card-widget card-clock"><div class="card-glass"><div class="card-background"><div class="card-content"><div id="hexo_electric_clock"><img class="entered loading" id="card-clock-loading" src="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/loading.gif" style="height: 120px; width: 100%;" data-ll-status="loading"/></div></div></div></div></div>';
    console.log('已挂载butterfly_clock_anzhiyu')
    if(parent_div_git) {
      parent_div_git.insertAdjacentHTML("afterbegin",item_html)
    }
  }
  var elist = 'null'.split(',');
  var cpage = location.pathname;
  var epage = 'all';
  var qweather_key = '56289903f0d448dfbe8262dba0175f70';
  var gaud_map_key = '01603f2b2d08d0e947bb101e9d9b148b';
  var baidu_ak_key = 'undefined';
  var flag = 0;
  var clock_rectangle = '112.982279,28.19409';
  var clock_default_rectangle_enable = 'false';

  for (var i=0;i<elist.length;i++){
    if (cpage.includes(elist[i])){
      flag++;
    }
  }

  if ((epage ==='all')&&(flag == 0)){
    butterfly_clock_anzhiyu_injector_config();
  }
  else if (epage === cpage){
    butterfly_clock_anzhiyu_injector_config();
  }
  </script><script src="https://widget.qweather.net/simple/static/js/he-simple-common.js?v=2.0"></script><script data-pjax src="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/clock.min.js"></script><!-- hexo injector body_end end --><script src="/dujie5416/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"tagMode":false,"debug":false,"model":{"jsonPath":"/dujie5416/live2dw/assets/tororo.model.json"},"display":{"position":"right","width":150,"height":350,"hOffset":20,"vOffset":-20},"mobile":{"show":false},"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/"});</script><script async>window.onload=function(){var a=document.createElement('script'),b=document.getElementsByTagName('script')[0];a.type='text/javascript',a.async=!0,a.src='/sw-register.js?v='+Date.now(),b.parentNode.insertBefore(a,b)};</script></body></html>